package org.streets.database.internal;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.streets.database.SQLTransaction;
import org.streets.database.SQLTransactionException;

/**
 * 
 * @author dzb
 *
 */
public class SQLTransactionImpl implements SQLTransaction {
	
	private Log log = LogFactory.getLog(getClass());
	
	private final Connection connection;
	// 1 need commit or rollback
	// 0 clear
	// -1 rollback only	
	private int _state = 1;  

	SQLTransactionImpl(Connection connection) {
		this.connection = connection;
	}
		
	/* (non-Javadoc)
	 * @see org.streets.database.Trans#getState()
	 */
	public int getState() {
		return _state;		
	}
	
	public void setState(int state) {
		_state = state;
	}
	
    /* (non-Javadoc)
	 * @see org.streets.database.Trans#rollback()
	 */
    public void rollback() {
        // prevent rollback more than once:
        if (_state == 0) return;
        // start rollback:
        if (log.isDebugEnabled())
            log.debug("Transaction rollback.");
        try {
            connection.rollback();
            connection.setAutoCommit(true);
            _state = 0;
        } catch(SQLException e) {
            throw new SQLTransactionException("Rollback transaction failed.", e);
        }
    }

    /* (non-Javadoc)
	 * @see org.streets.database.Trans#commit()
	 */
    public void commit() {
        if (_state < 0)  {
        	rollback();
            return;
        }
        if (_state == 0) return;
        if (log.isDebugEnabled())
            log.debug("Transaction commit.");
        try {
            connection.commit();
            connection.setAutoCommit(true);
            _state = 0;
        }
        catch(SQLException e) {
            throw new SQLTransactionException("Commit transaction failed.", e);
        }
    }
}
